from typing import List, Optional
from app.database.database import get_db_with_dict_factory
from app.models.article import ArticleResponse as Article
import uuid
from datetime import datetime
from app.models.article import ArticleCreate, ArticleUpdate
import json

class ArticleService:
    def __init__(self):
        self.db = get_db_with_dict_factory()

    async def generate_article(self, topic: str, references: List[str], length: str, style: str) -> dict:
        """
        生成文章内容
        """
        # TODO: 实现AI文章生成逻辑
        # 这里先创建一个示例文章
        article = Article(
            title=f"关于{topic}的文章",
            content=f"这是一篇关于{topic}的{length}篇{style}风格的文章...",
            user_id=str(uuid.uuid4()),  # 临时使用，后续需要从认证用户中获取
            summary=f"{topic}的概述"
        )
        
        # 保存到数据库
        cursor = self.db.cursor()
        cursor.execute("""
            INSERT INTO articles (id, user_id, title, content, summary, status)
            VALUES (?, ?, ?, ?, ?, ?)
        """, (article.id, article.user_id, article.title, article.content, article.summary, article.status))
        
        # 保存文章参数
        cursor.execute("""
            INSERT INTO article_params (id, article_id, topic, style, length)
            VALUES (?, ?, ?, ?, ?)
        """, (str(uuid.uuid4()), article.id, topic, style, length))
        
        # 保存参考链接
        for ref in references:
            cursor.execute("""
                INSERT INTO reference_urls (id, article_id, url)
                VALUES (?, ?, ?)
            """, (str(uuid.uuid4()), article.id, ref))
        
        self.db.commit()
        
        return {
            "id": article.id,
            "title": article.title,
            "content": article.content,
            "summary": article.summary,
            "created_at": article.created_at,
            "updated_at": article.updated_at,
            "status": article.status,
            "view_count": article.view_count
        }

    async def get_all_articles(self) -> List[dict]:
        """
        获取所有文章列表
        """
        cursor = self.db.cursor()
        cursor.execute("""
            SELECT a.*, ap.topic, ap.style, ap.length
            FROM articles a
            LEFT JOIN article_params ap ON a.id = ap.article_id
            ORDER BY a.created_at DESC
        """)
        return cursor.fetchall()

    async def get_article(self, article_id: str) -> Optional[dict]:
        """
        获取单篇文章详情
        """
        cursor = self.db.cursor()
        cursor.execute("""
            SELECT * FROM articles WHERE id = ?
        """, (article_id,))
        article = cursor.fetchone()
        
        if article:
            # 处理 references 字段，将 JSON 字符串转换为 Python 列表
            if article.get('references'):
                try:
                    article['references'] = json.loads(article['references'])
                except json.JSONDecodeError:
                    article['references'] = []
            else:
                article['references'] = []
        
        return article

    async def create_article(self, article_data: ArticleCreate, user_id: str = None):
        """创建新文章"""
        cursor = self.db.cursor()
        
        article_id = str(uuid.uuid4())
        now = datetime.now().isoformat()
        
        # 处理状态，如果没有提供则默认为草稿
        status = article_data.status if article_data.status else 'draft'
        
        # 插入文章 - 注意 references 列名需要用引号括起来
        cursor.execute(
            """
            INSERT INTO articles (
                id, title, content, status, template_id, "references", reference_content, 
                reference_style, length, style, user_id, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                article_id, article_data.title, article_data.content, status,
                article_data.template_id, json.dumps(article_data.references),
                article_data.reference_content, article_data.reference_style,
                article_data.length, article_data.style, user_id, now, now
            )
        )
        
        self.db.commit()
        
        return await self.get_article(article_id)

    async def update_article(self, article_id: str, article_data: ArticleUpdate):
        """更新文章"""
        cursor = self.db.cursor()
        
        # 检查文章是否存在
        cursor.execute("SELECT * FROM articles WHERE id = ?", (article_id,))
        article = cursor.fetchone()
        
        if not article:
            return None
            
        # 准备更新的字段
        update_fields = []
        params = []
        
        # 检查每个可能的字段是否需要更新
        if article_data.title is not None:
            update_fields.append("title = ?")
            params.append(article_data.title)
        
        if article_data.content is not None:
            update_fields.append("content = ?")
            params.append(article_data.content)
        
        if article_data.status is not None:
            update_fields.append("status = ?")
            params.append(article_data.status)
        
        if article_data.template_id is not None:
            update_fields.append("template_id = ?")
            params.append(article_data.template_id)
        
        if article_data.references is not None:
            update_fields.append("\"references\" = ?")
            params.append(json.dumps(article_data.references))
        
        if article_data.reference_content is not None:
            update_fields.append("reference_content = ?")
            params.append(article_data.reference_content)
        
        if article_data.reference_style is not None:
            update_fields.append("reference_style = ?")
            params.append(article_data.reference_style)
        
        if article_data.length is not None:
            update_fields.append("length = ?")
            params.append(article_data.length)
        
        if article_data.style is not None:
            update_fields.append("style = ?")
            params.append(article_data.style)
        
        # 更新时间戳
        update_fields.append("updated_at = ?")
        now = datetime.now().isoformat()
        params.append(now)
        
        # 添加文章ID到参数列表
        params.append(article_id)
        
        # 执行更新
        cursor.execute(
            f"""
            UPDATE articles 
            SET {', '.join(update_fields)}
            WHERE id = ?
            """,
            params
        )
        
        self.db.commit()
        
        return await self.get_article(article_id)

    async def publish_article(self, article_id: str) -> Optional[dict]:
        """发布文章"""
        cursor = self.db.cursor()
        now = datetime.utcnow()

        cursor.execute("""
            UPDATE articles
            SET status = 'published', updated_at = ?
            WHERE id = ?
        """, (now, article_id))

        self.db.commit()
        return await self.get_article(article_id)

    async def get_articles(self, page: int = 1, limit: int = 10, search: Optional[str] = None):
        """获取文章列表，支持分页和搜索"""
        cursor = self.db.cursor()
        
        try:
            # 构建查询
            query = "SELECT * FROM articles"
            count_query = "SELECT COUNT(*) as total FROM articles"
            params = []
            
            # 添加搜索条件
            if search:
                query += " WHERE title LIKE ? OR content LIKE ?"
                count_query += " WHERE title LIKE ? OR content LIKE ?"
                search_param = f"%{search}%"
                params.extend([search_param, search_param])
            
            # 添加排序和分页
            query += " ORDER BY updated_at DESC LIMIT ? OFFSET ?"
            params.extend([limit, (page - 1) * limit])
            
            print(f"执行查询: {query} 参数: {params}")
            
            # 执行查询
            cursor.execute(query, params)
            articles = cursor.fetchall()
            
            # 处理每篇文章的 references 字段，将 JSON 字符串转换为 Python 列表
            for article in articles:
                if article.get('references'):
                    try:
                        article['references'] = json.loads(article['references'])
                    except json.JSONDecodeError:
                        article['references'] = []
                else:
                    article['references'] = []
            
            print(f"查询结果: {articles}")
            
            # 获取总数
            cursor.execute(count_query, params[:-2] if search else [])
            total_result = cursor.fetchone()
            total = total_result["total"] if total_result else 0
            
            print(f"总数查询结果: {total}")
            
            return {
                "items": articles if articles else [],
                "total": total,
                "page": page,
                "limit": limit
            }
        except Exception as e:
            print(f"获取文章列表出错: {str(e)}")
            import traceback
            print(traceback.format_exc())
            return {
                "items": [],
                "total": 0,
                "page": page,
                "limit": limit
            }

    async def delete_article(self, article_id: str):
        """删除文章"""
        cursor = self.db.cursor()
        
        # 检查文章是否存在
        cursor.execute("SELECT * FROM articles WHERE id = ?", (article_id,))
        article = cursor.fetchone()
        
        if not article:
            return False
        
        # 删除文章
        cursor.execute("DELETE FROM articles WHERE id = ?", (article_id,))
        self.db.commit()
        
        return True

    def __del__(self):
        """
        确保数据库连接被正确关闭
        """
        if hasattr(self, 'db'):
            self.db.close() 